<?php

namespace wechat;

class WechatAccounts{
    /**
     * 获取requestCode的api接口
     * @var string
     */
    protected $GetRequestCodeURL = 'https://open.weixin.qq.com/connect/qrconnect';

    /**
     * 获取access_token的api接口
     * @var string
     */
//     protected $GetAccessTokenURL = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    protected $GetAccessTokenURL = 'https://api.weixin.qq.com/cgi-bin/token';


    /**
     * API根路径
     * @var string
     */
    protected $ApiBase = 'https://api.weixin.qq.com/';

    public function __construct($token = null){

        $accesstoken = cache('AccessToken');

        if(!$accesstoken){

            $temp = $this->getAccessToken();

            cache('AccessToken',$temp['access_token'],7000);
        }
    }

    public function AccessToken(){
        return cache('AccessToken');
    }

    public function getRequestCodeURL(){
        $this->config();
        $params = array(
            'appid' => $this->AppKey,
            'redirect_uri'=>$this->Callback,
            'response_type'=>'code',
            'scope'=>'snsapi_login'
        );
        return $this->GetRequestCodeURL . '?' . http_build_query($params);
    }

    /**
     * 获取access_token
     */
    public function getAccessToken(){

        $params = array(
            'appid'     => config('wechat.oauth.appid'),
            'secret'    => config('wechat.oauth.appsecret'),
            'grant_type'    => 'client_credential',
        );

        $data = $this->http_request($this->GetAccessTokenURL, $params);

        return json_decode($data,true);
    }


    /*
     * 设置公众号菜单
     */
    public function SetMenu($data){
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.cache('AccessToken');
        $data = $this->http_request( $url , $data,false);
        return json_decode($data, true);

    }


    /**
     * 发送curl请求
     * @param $url string
     * @param return array|mixed
     */
    //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
    function http_request($url,$post='',$query=true,$cookie='', $returnCookie=0){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);

            if($query){
                $post = http_build_query($post);
            }
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if($returnCookie){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        }else{
            return $data;
        }
    }
     /**
     * 组装接口调用参数 并调用接口
     * @param  string $api    微博API
     * @param  string $param  调用API的额外参数
     * @param  string $method HTTP请求方法 默认为GET
     * @return json
     */
//    public function call($api, $param = '', $method = 'GET', $multi = false){
//        /* 腾讯微博调用公共参数 */
//        $params = array(
//            'access_token'       => $this->Token['access_token'],
//            'openid'             => $this->openid(),
//        );
//
//        $vars = $this->param($params, $param);
//        $data = $this->http($this->url($api), $vars, $method, array(), $multi);
//        return json_decode($data, true);
//    }


    /**
     * 解析access_token方法请求后的返回值
     */
//    protected function parseToken($result, $extend){
//        $data = json_decode($result,true);
//        //parse_str($result, $data);
//        if($data['access_token'] && $data['expires_in']){
//            $this->Token    = $data;
////             $data['openid'] = $this->openid();
//            return $data;
//        } else
//            throw new Exception("获取微信 ACCESS_TOKEN 出错：{$result}");
//    }

    /**
     * 获取当前授权应用的openid
     */
//    public function openid(){
//        $data = $this->Token;
//        if(!empty($data['openid']))
//            return $data['openid'];
//        else
//            exit('没有获取到微信用户ID！');
//    }
//
//    public function xmlencode(){
//
//    }
    public function xmldecode($data){

        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }


    public function checkSignature(){
//
        if( input('echostr') ){
            exit(input('echostr'));
        }

//        $signature = input('signature');
//        $timestamp = input('timestamp');
//        $nonce = input('nonce');
//
//        $tmpArr = array(timestamp, $nonce);
//        sort($tmpArr, SORT_STRING);
//        $tmpStr = implode( $tmpArr );
//        $tmpStr = sha1( $tmpStr );
//
//        if( $signature ){
//            exit(input('echostr'));
//        }

    }


//
//    public function GetQrcode($num){
//        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.F('AccessToken');
//        $arr = array(
//            'expire_seconds'=>604800,
//            'action_name'   => 'QR_LIMIT_SCENE',
//            'action_info'   => array('scene'=>array('scene_id'=>$num)),
//        );
//        $data = $this->http( $url , json_encode($arr), 'POST',array(),true);
//        return json_decode($data, true);
//
//    }
//

//
//    public function GetWebOpenId(){
//        $this->config();
//        if(I('code')){
//            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->AppKey.'&secret='.$this->AppSecret.'&code='.I('code').'&grant_type=authorization_code';
//            $data = $this->http( $url,'' );
//            return json_decode($data, true);
//        }
//        header('location: https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->AppKey.'&redirect_uri=http://'.$_SERVER['HTTP_HOST']. urlencode(U())  .'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect');
//        exit();
//    }
//
//    public function SetMesg( $arr ){
//        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.F('AccessToken');
//        $data = $this->http( $url , json_encode($arr), 'POST',array(),true);
//        return json_decode($data, true);
//    }
//
//    public function SetMesgcustom( $arr ){
//        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.F('AccessToken');
//        $data = $this->http( $url , json_encode($arr,JSON_UNESCAPED_UNICODE), 'POST',array(),true);
//        return json_decode($data, true);
//
//    }

}

